
package PurchaseGUIs;

import CustomerGUIs.EditCustomerForm;
import Model.*;
import Supermarket.AppMessages;
import java.awt.Window;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.ListIterator;
import javax.persistence.*;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author bagi + Manolis 
 */
public class CartForm extends javax.swing.JDialog {

    private static EntityManager em;
    private Customer customer;
    private Purchase purchase;
    private List<ProductPurchase> productPurchaseList;
    private List<Checks> SelectedChecksList;
    private float totalAmount = 0;
    private int totalPoints = 0;
    private int maxSelectedChecks = 0;
    private int selectedChecks = 0;
    private boolean completed;
    private boolean checkSelectionAllowed = false;
    private Window thisParent = this;
    //Διαμόρφωσης αριθμητικών πεδίων - δεκαδικές τιμές 
    DecimalFormat df = new DecimalFormat("###.##");
           
    /**
     * Creates new form NewJFrame
     */
    public CartForm(java.awt.Frame parent, boolean modal){
       super(parent, modal); 
       em = InternalDBManager.getEm();
       initComponents();
       this.setIconImage(new
                ImageIcon(getClass().getResource("..\\Images\\cart.png")).getImage()); 
    }
     
    public CartForm(java.awt.Frame parent, boolean modal, Purchase p,Customer c) {
       super(parent, modal);
       em = InternalDBManager.getEm();
       if(!em.isOpen()){
           em.getTransaction().begin();
       }
       //αρχικοποίηση μεταβλητών
       this.purchase = p;
       this.productPurchaseList = purchase.getProductPurchaseList();
       this.customer=c;
       this.SelectedChecksList = new ArrayList<>();
       this.completed = false;
       initComponents();
       setDataOnCartForm();
       this.setIconImage(new
                ImageIcon(getClass().getResource("..\\Images\\cart.png")).getImage()); 
    }

    //η μέθοδος γεμίζει της φόρμας καλαθιού με τα δεδομένα της τρέχουσας αγοράς
    public void setDataOnCartForm(){
       CustomerNameField.setText(customer.getFirstName()+" "+
               customer.getLastName());
       setDataOnProductPurchaseTable();
       calcTotalAmount();
       calcTotalPoints();
       setDataOnChecksTable();
    }
         
    //ενημέρωση πίνακα αγοράς προϊόντων με τα επιλεγμένα από το πελάτη προϊόντα
    public void setDataOnProductPurchaseTable(){
       //Δημιουργία μοντέλου πίνακα προϊόντων
       DefaultTableModel modelListOfProducts = (DefaultTableModel) ListOfProducts.getModel();
       //εμφάνιση των προϊόντων αγοράς του πελάτη 
       for (ProductPurchase pp : productPurchaseList) {
            //καθορισμός τιμών για τα κελια του πίνακα-εισαγωγή ενός προϊόντος σε κάθε γραμμή
            Object[] product = new Object[4];
            product[0] = pp.getProductId().getProductName();
            product[1] = pp.getProductId().getPoints() * pp.getQuantity();
            product[2] = pp.getProductId().getPrice() * pp.getQuantity();
            product[3] = new Integer (pp.getQuantity());
            //ενημέρωση πίνακα
            modelListOfProducts.addRow(product);
            }
    }
    
    //ενημέρωση πίνακα με το συνολικό ποσό αγοράς
    public void calcTotalAmount(){
        for (ProductPurchase pp : productPurchaseList) {
            totalAmount +=  pp.getProductId().getPrice() * pp.getQuantity();
        }
        AmountField.setText(String.valueOf(df.format(totalAmount)));
        //υπολογισμός επιτρεπόμενου πλήθους επιταγών για κάλυψη αγοράς
        maxSelectedChecks = (int) (totalAmount /6);
    }
    
    //ενημέρωση πίνακα με τους συνολικούς πόντους
    public void calcTotalPoints(){
        for (ProductPurchase pp : productPurchaseList) {
            totalPoints +=  pp.getProductId().getPoints() * pp.getQuantity();
        }
        PointsField.setText(String.valueOf(totalPoints));
    }
     
    //μέθοδος τροποποίησης της λειτουργικότητας του πίνακα επιταγών
    public void setDataOnChecksTable(){
       //Δημιουργία μοντέλου πίνακα επιταγών-καθορισμός editor 2 τελευταίων στηλών σε check box
       DefaultTableModel modelListOfChecks = (DefaultTableModel) ListOfChecks.getModel();
       //εμφάνιση των επιταγών του πελάτη 
       for (Checks c : customer.getChecksList()) {
            //εισαγωγή μίας επιταγής σε κάθε γραμμή
            Object[] check = new Object[4];
            check[0] = c.getCheckId();
            check[1] = c.getTimeStamp();
            check[2] = c.getStatus();
            check[3] = false;
            //ενημέρωση πίνακα
            modelListOfChecks.addRow(check);
            }
       if (totalAmount>6)
           checkSelectionAllowed = true;
       //εάν η αξία της αγοράς είναι μεγαλύτερη από 6€, ενεργοποιείται ο πίνακας επιταγών
       appendListOfChecksModel(checkSelectionAllowed);
    }
    
    public void appendListOfChecksModel(boolean flag){  
           ListOfChecks.setEnabled(flag);
           ListOfChecks.setRowSelectionAllowed(flag);
           ListOfChecks.setColumnSelectionAllowed(!flag);
    }
    
    //ενημέρωση αντικειμένου αγοράς
    public void updatePurchaseObject(){
        purchase.setProductPurchaseList(productPurchaseList);
        purchase.setAmount(totalAmount);
        purchase.setPointsEarned(totalPoints);
        purchase.setSuccess("temp");
        em.persist(purchase);
        em.getTransaction().commit();
        
    } 
    
    //ενημέρωση επιταγών και πόντων πελάτη
    public void updateCustomerObject(){
        //για όλες τις επιταγές που έχουν ακυρωθεί
        for (Checks check : SelectedChecksList){
            //βρες τες και άλλαξε το status τους
            customer.getChecksList().get(customer.getChecksList().indexOf(check)).setStatus(false);
        }
        //υπολογισμός πόντων 
        int newPoints = customer.getAvailablePoints() + totalPoints;
        //εάν οι συνολικοί πόντοι του πελάτη είναι > 200
        if (newPoints>=200){
            //υπολόγισε τις νέες επιταγές του πελάτη
            int noOfChecks = (int) newPoints/200;
            //καθόρισε τους πόντους του
            customer.setAvailablePoints(newPoints-noOfChecks*200);
            //και πρόσθεσε τις νέες επιταγές στο πελάτη
            updateCustomerCheckList(noOfChecks);
       }else
            //αλλιώς (πόντοι <200) αποθήκευσε το σύνολο των πόντων
            customer.setAvailablePoints(newPoints);
    }
    
    //ενημέρωση επιταγών πελάτη
    public void updateCustomerCheckList(int noOfCheks){
        for(int i=0;i<noOfCheks;i++){
            Checks checks = new Checks();
            checks.setCustomer(customer);
            checks.setStatus(true);
            checks.setTimeStamp(new Date());
            customer.addToChecksList(checks);
            em.persist(checks);
        }
    }
            
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        dateFormatRenderer1 = new Supermarket.DateFormatRenderer();
        purchaseProductsPanel = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        CustomerNameField = new javax.swing.JTextField();
        jScrollPane2 = new javax.swing.JScrollPane();
        ListOfProducts = new javax.swing.JTable();
        jSeparator1 = new javax.swing.JSeparator();
        jLabel5 = new javax.swing.JLabel();
        AmountField = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        PointsField = new javax.swing.JTextField();
        ChecksPanel = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        ListOfChecks = new javax.swing.JTable();
        DeliveryPanel = new javax.swing.JPanel();
        jLabel4 = new javax.swing.JLabel();
        StoreReceiptRadioBtn = new javax.swing.JRadioButton();
        HomeDeliveryRadioBtn = new javax.swing.JRadioButton();
        jSeparator2 = new javax.swing.JSeparator();
        PurchaseButton = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jSeparator3 = new javax.swing.JSeparator();
        jLabel3 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jSeparator4 = new javax.swing.JSeparator();
        jLabel9 = new javax.swing.JLabel();
        NumberOfSelectedChecksLabel = new javax.swing.JLabel();
        TotalDiscountLabel = new javax.swing.JLabel();
        TotalLabel = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();

        dateFormatRenderer1.setText("dateFormatRenderer1");

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Προβολή καλαθιού");
        setAlwaysOnTop(true);

        purchaseProductsPanel.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel2.setText("Ονοματεπώνυμο πελάτη:");

        CustomerNameField.setEditable(false);
        CustomerNameField.setBackground(new java.awt.Color(204, 204, 204));
        CustomerNameField.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        CustomerNameField.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        CustomerNameField.setDisabledTextColor(new java.awt.Color(0, 0, 153));
        CustomerNameField.setEnabled(false);

        ListOfProducts.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        ListOfProducts.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        ListOfProducts.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Προϊόν", "Πόντοι", "Τιμή", "Ποσότητα"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.Integer.class, java.lang.Float.class, java.lang.Integer.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        ListOfProducts.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        ListOfProducts.setRowHeight(20);
        ListOfProducts.setSurrendersFocusOnKeystroke(true);
        jScrollPane2.setViewportView(ListOfProducts);
        if (ListOfProducts.getColumnModel().getColumnCount() > 0) {
            ListOfProducts.getColumnModel().getColumn(0).setResizable(false);
            ListOfProducts.getColumnModel().getColumn(0).setPreferredWidth(300);
            ListOfProducts.getColumnModel().getColumn(1).setResizable(false);
            ListOfProducts.getColumnModel().getColumn(1).setPreferredWidth(30);
            ListOfProducts.getColumnModel().getColumn(2).setResizable(false);
            ListOfProducts.getColumnModel().getColumn(2).setPreferredWidth(25);
            ListOfProducts.getColumnModel().getColumn(3).setResizable(false);
            ListOfProducts.getColumnModel().getColumn(3).setPreferredWidth(50);
        }

        jLabel5.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel5.setText("Συνολική αξία αγοράς:");

        AmountField.setEditable(false);
        AmountField.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        AmountField.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        AmountField.setText("0.00");
        AmountField.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jLabel6.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel6.setText("Πόντοι αγοράς:");

        PointsField.setEditable(false);
        PointsField.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        PointsField.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        PointsField.setText("0");
        PointsField.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

        javax.swing.GroupLayout purchaseProductsPanelLayout = new javax.swing.GroupLayout(purchaseProductsPanel);
        purchaseProductsPanel.setLayout(purchaseProductsPanelLayout);
        purchaseProductsPanelLayout.setHorizontalGroup(
            purchaseProductsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(purchaseProductsPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(purchaseProductsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2)
                    .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(purchaseProductsPanelLayout.createSequentialGroup()
                        .addComponent(jLabel6)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(PointsField, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(AmountField, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(purchaseProductsPanelLayout.createSequentialGroup()
                        .addGroup(purchaseProductsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(CustomerNameField, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        purchaseProductsPanelLayout.setVerticalGroup(
            purchaseProductsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, purchaseProductsPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(CustomerNameField, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 211, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(purchaseProductsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(AmountField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6)
                    .addComponent(PointsField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        ChecksPanel.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel1.setText("Κωδικοί επιταγών:");

        ListOfChecks.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        ListOfChecks.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        ListOfChecks.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Αρ.Επιταγής", "Ημεριμηνία", "Έγκυρη", "Επιλογή"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.Object.class, java.lang.Boolean.class, java.lang.Boolean.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        ListOfChecks.setToolTipText("Επιτρέπεται η επιλογή μόνο ενεργών επιταγών");
        ListOfChecks.setColumnSelectionAllowed(true);
        ListOfChecks.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        ListOfChecks.setEnabled(false);
        ListOfChecks.setRowHeight(20);
        ListOfChecks.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                ListOfChecksMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(ListOfChecks);
        ListOfChecks.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        if (ListOfChecks.getColumnModel().getColumnCount() > 0) {
            ListOfChecks.getColumnModel().getColumn(0).setResizable(false);
            ListOfChecks.getColumnModel().getColumn(0).setPreferredWidth(70);
            ListOfChecks.getColumnModel().getColumn(1).setResizable(false);
            ListOfChecks.getColumnModel().getColumn(1).setPreferredWidth(70);
            ListOfChecks.getColumnModel().getColumn(1).setCellRenderer(dateFormatRenderer1);
            ListOfChecks.getColumnModel().getColumn(2).setResizable(false);
            ListOfChecks.getColumnModel().getColumn(2).setPreferredWidth(50);
            ListOfChecks.getColumnModel().getColumn(3).setResizable(false);
            ListOfChecks.getColumnModel().getColumn(3).setPreferredWidth(80);
        }

        javax.swing.GroupLayout ChecksPanelLayout = new javax.swing.GroupLayout(ChecksPanel);
        ChecksPanel.setLayout(ChecksPanelLayout);
        ChecksPanelLayout.setHorizontalGroup(
            ChecksPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, ChecksPanelLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(ChecksPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 289, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addGap(57, 57, 57))
        );
        ChecksPanelLayout.setVerticalGroup(
            ChecksPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(ChecksPanelLayout.createSequentialGroup()
                .addGap(9, 9, 9)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        jLabel4.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel4.setText("Τρόπος αποστολής:");

        StoreReceiptRadioBtn.setBackground(new java.awt.Color(255, 255, 255));
        StoreReceiptRadioBtn.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        StoreReceiptRadioBtn.setText("Παραλαβή κατάστημα");
        StoreReceiptRadioBtn.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
        StoreReceiptRadioBtn.setBorderPainted(true);
        StoreReceiptRadioBtn.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                StoreReceiptRadioBtnStateChanged(evt);
            }
        });

        HomeDeliveryRadioBtn.setBackground(new java.awt.Color(255, 255, 255));
        HomeDeliveryRadioBtn.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        HomeDeliveryRadioBtn.setText("Αποστολή στο χώρο");
        HomeDeliveryRadioBtn.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
        HomeDeliveryRadioBtn.setBorderPainted(true);
        HomeDeliveryRadioBtn.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                HomeDeliveryRadioBtnStateChanged(evt);
            }
        });

        javax.swing.GroupLayout DeliveryPanelLayout = new javax.swing.GroupLayout(DeliveryPanel);
        DeliveryPanel.setLayout(DeliveryPanelLayout);
        DeliveryPanelLayout.setHorizontalGroup(
            DeliveryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(DeliveryPanelLayout.createSequentialGroup()
                .addComponent(jLabel4)
                .addGap(18, 18, 18)
                .addGroup(DeliveryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(HomeDeliveryRadioBtn, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(StoreReceiptRadioBtn, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(0, 0, Short.MAX_VALUE))
        );
        DeliveryPanelLayout.setVerticalGroup(
            DeliveryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(DeliveryPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(DeliveryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(StoreReceiptRadioBtn))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(HomeDeliveryRadioBtn)
                .addContainerGap())
        );

        PurchaseButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/purchase.png"))); // NOI18N
        PurchaseButton.setText("Ολοκλήρωση αγοράς");
        PurchaseButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                PurchaseButtonActionPerformed(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel3.setText("Επιταγές:");

        jLabel7.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel7.setText("Επιλεγμένες:");

        jLabel8.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel8.setText("Συνολική έκπτωση:");

        jLabel9.setText("Υπόλοιπο:");

        NumberOfSelectedChecksLabel.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        NumberOfSelectedChecksLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        NumberOfSelectedChecksLabel.setText(" ");

        TotalDiscountLabel.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        TotalDiscountLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        TotalDiscountLabel.setText(" ");

        TotalLabel.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        TotalLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        TotalLabel.setText(" ");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jSeparator3)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel8)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(TotalDiscountLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 101, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel7)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(NumberOfSelectedChecksLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel9)
                        .addGap(27, 27, 27)
                        .addComponent(TotalLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap())
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jSeparator4, javax.swing.GroupLayout.DEFAULT_SIZE, 209, Short.MAX_VALUE)
                    .addContainerGap()))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(NumberOfSelectedChecksLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel8)
                    .addComponent(TotalDiscountLabel))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel9)
                    .addComponent(TotalLabel))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addGap(94, 94, 94)
                    .addComponent(jSeparator4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(32, Short.MAX_VALUE)))
        );

        jLabel10.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/Fullbasket_128.png"))); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(PurchaseButton))
                    .addComponent(jSeparator2)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(purchaseProductsPanel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(ChecksPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 313, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(DeliveryPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                        .addComponent(jLabel10)
                                        .addGap(51, 51, 51)))))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(purchaseProductsPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 322, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel10))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(ChecksPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(DeliveryPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(PurchaseButton)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void PurchaseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_PurchaseButtonActionPerformed
        ////Με την ολοκλήρωση επιλογής των προϊόντων, ελέγχει εάν έχει επιλεγεί τρόπος παράδοσης
        if (!HomeDeliveryRadioBtn.isSelected() && !StoreReceiptRadioBtn.isSelected()){
        //εάν όχι, ενημερώνει το πελάτη
            JOptionPane.showMessageDialog(this, "Παρακαλώ, επιλέξτε τον τρόπο αποστολής των προϊόντων.", 
                    "ΠΡΟΣΟΧΗ", JOptionPane.WARNING_MESSAGE);
         } else {
            //διαφορετικά, ενημερώνει το σύνολο της αγοράς, 
            totalAmount=totalAmount-6*selectedChecks;
            //το σχετικό πεδίο του πίνακα
            AmountField.setText(String.valueOf(df.format(totalAmount)));
            //ενημερώνεται το αντικείμενο αγοράς με τα νέα στοιχεία και
            updatePurchaseObject();
            //και καλείται η φόρμα ολοκλήρωσης αγοράς
            CheckCustomerCard checkCustomerCard = new CheckCustomerCard(this, customer);
            CreditCardLog creditLog = checkCustomerCard.getCreditCardLog();
            updateDatabase (creditLog); 
            this.completed = true;
            this.setVisible(false);
        }
    }//GEN-LAST:event_PurchaseButtonActionPerformed
   
    
    private void HomeDeliveryRadioBtnStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_HomeDeliveryRadioBtnStateChanged
        //εάν επιλεχθεί το κουμπί "Αποστολή στο κατάστημα", γίνεται true το πεδίο delivery
        if (HomeDeliveryRadioBtn.isSelected()){
            StoreReceiptRadioBtn.setSelected(false);
            //αν ο πελάτης δεν έχει καταχωρημένη διεύθυνση
          try{
                if (customer.getAddress().length()>0){
                    purchase.setDelivery(true);
                } else {
                    throw new NullPointerException();
                }
          }catch(NullPointerException e){
                //διάβασε τη διεύθυνση του πελάτη
                customer.setAddress( JOptionPane.showInputDialog(thisParent, "Παρακαλώ εισάγετε την διεύθυνσή σας:", 
                    "Εισαγωγή διεύθυνσης",JOptionPane.OK_OPTION));
                HomeDeliveryRadioBtn.setSelected(true);
          }
        }
    }//GEN-LAST:event_HomeDeliveryRadioBtnStateChanged

    private void StoreReceiptRadioBtnStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_StoreReceiptRadioBtnStateChanged
        //εάν επιλεχθεί το κουμπί "Αποστολή στο κατάστημα", γίνεται false το πεδίο delivery
        if (StoreReceiptRadioBtn.isSelected()){
                purchase.setDelivery(false);
                HomeDeliveryRadioBtn.setSelected(false);
        }        
    }//GEN-LAST:event_StoreReceiptRadioBtnStateChanged

    //έλεγχος status επιταγής και ενημέρωση πελάτη κατά την επιλογή
    private void ListOfChecksMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ListOfChecksMouseClicked
        //εάν επιτρέπεται η επιλογή γραμμής-επιταγής από το πίνακα (αξία αγοράς>6€)
        try{
            if (selectedChecks == maxSelectedChecks){
                //απενεργοποιεί τον πίνακα τον επιταγών
                appendListOfChecksModel(false);
                //ενημερώνει το πελάτη
                AppMessages.MaxChecksSelectionMessage(this);
            } else {
                if(ListOfChecks.getRowSelectionAllowed()){
                    //Επιλογή επιταγής από τη λίστα
                    int selectedRow = ListOfChecks.getSelectedRow();
                    Checks check = customer.getChecksList().get(selectedRow);
                    //εάν επιλεγεί γραμμή με ακυρωμένη επιταγή
                    if (!check.getStatus()){
                        //ενημερώνει το πελάτη
                        AppMessages.ActionNotAcceptedMessage(this);
                    } else {
                        //αν μια επιταγή είναι επιλεγμένη
                        if ((boolean) ListOfChecks.getValueAt(selectedRow, 3)== true){
                            //απορεπιλέγεται
                            ListOfChecks.setValueAt(false , selectedRow, 3);
                            //μειώνεται ο αριμός επιλεγμένων
                            selectedChecks--; 
                            //ενημέρωση της λίστας των επιλεγμένων
                            SelectedChecksList.remove(check);
                        }else{
                            //αλλιώς επιλέγεται η επιταγή 
                            ListOfChecks.setValueAt(true, selectedRow, 3);
                            //αυξάνεται ο αριθμός των επιλεγμένων
                            selectedChecks++;
                            //ενημέρωση της λίστας των επιλεγμένων
                            SelectedChecksList.add(check);
                        }
                        NumberOfSelectedChecksLabel.setText("" + selectedChecks);
                        TotalDiscountLabel.setText(String.valueOf("Ευρώ " + selectedChecks * 6));
                        TotalLabel.setText(String.valueOf(df.format(totalAmount - selectedChecks * 6)));
                    } 
                }
           }
        } catch (ArrayIndexOutOfBoundsException e){
                //ενημερώνει το πελάτη όταν η αξία είναι <6€ ότι
                AppMessages.ActionNotPermittedMessage(this); 
        }
    }//GEN-LAST:event_ListOfChecksMouseClicked

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(CartForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                CartForm dialog = new CartForm(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField AmountField;
    private javax.swing.JPanel ChecksPanel;
    private javax.swing.JTextField CustomerNameField;
    private javax.swing.JPanel DeliveryPanel;
    private javax.swing.JRadioButton HomeDeliveryRadioBtn;
    private javax.swing.JTable ListOfChecks;
    private javax.swing.JTable ListOfProducts;
    private javax.swing.JLabel NumberOfSelectedChecksLabel;
    private javax.swing.JTextField PointsField;
    private javax.swing.JButton PurchaseButton;
    private javax.swing.JRadioButton StoreReceiptRadioBtn;
    private javax.swing.JLabel TotalDiscountLabel;
    private javax.swing.JLabel TotalLabel;
    private Supermarket.DateFormatRenderer dateFormatRenderer1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JSeparator jSeparator3;
    private javax.swing.JSeparator jSeparator4;
    private javax.swing.JPanel purchaseProductsPanel;
    // End of variables declaration//GEN-END:variables

    private void updateDatabase(CreditCardLog creditCardLog) {
       if(!em.getTransaction().isActive())
           em.getTransaction().begin();
       
        purchase.setSuccess(String.valueOf(creditCardLog.getSuccess()));
        
        List<PurchaseAttempts> purchaseAttemptsList = new ArrayList<>();
        
        //αν έχει γίνει αποδεκτή η συναλλαγή
        if (creditCardLog.getSuccess()){
                updateCustomerObject();
        }
        int i=0;
        //για καθε στοιχείο της λίστας Attempt της CreditCardLog
        for(ListIterator<Date> iterator = creditCardLog.getAttemptsList().listIterator(); iterator.hasNext();){
             //φτιάχνει και συμπληρώνει ένα αντικείμενο PurchaseAttempts
             PurchaseAttemptsPK purchaseAttemptsPK = new PurchaseAttemptsPK(i, purchase.getPurchaseId());
             PurchaseAttempts purchaseAttempt = new PurchaseAttempts();
             purchaseAttempt.setPurchaseAttemptsPK(purchaseAttemptsPK);
             purchaseAttempt.setTimeStamp( iterator.next());
             purchaseAttempt.setThreadName("Main");
             purchaseAttemptsList.add(purchaseAttempt);
             i++;
        }
        //Αποθηκεύει την αντίστοιχη λίστα
        purchase.setPurchaseAttemptsList(purchaseAttemptsList);
        em.persist(purchase);
        em.persist(customer);
        //em.persist(purchase);
        em.getTransaction().commit();
    }
    
    //επιστρέφει μια σημαία για την ολοκλήρωση της συναλλαγής
    public boolean getCompleted(){
        return this.completed;
    } 
    
}
